﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Ldy.Core
{
    class Ept
    {
		private static readonly string myKey = "32783390";
		/// <summary>
		/// 加密方法
		/// </summary>
		/// <param name="enStr">需要加密字符串</param>
		/// <returns>加密后的字符串</returns>
		public static string Encrypt(string enStr)
		{
			try
			{
				DESCryptoServiceProvider des = new DESCryptoServiceProvider();
				//把字符串放到byte数组中
				//原来使用的UTF8编码，我改成Unicode编码了，不行
				byte[] inputByteArray = Encoding.Default.GetBytes(enStr);
				//建立加密对象的密钥和偏移量
				//使得输入密码必须输入英文文本
				des.Key = ASCIIEncoding.ASCII.GetBytes(myKey);
				des.IV = ASCIIEncoding.ASCII.GetBytes(myKey);
				MemoryStream ms = new MemoryStream();
				CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
				cs.Write(inputByteArray, 0, inputByteArray.Length);
				cs.FlushFinalBlock();
				string ret = "";
				foreach (byte b in ms.ToArray())
				{
					ret = ret + string.Format("{0:X2}", b);
				}
				return ret;
			}
			catch (Exception ex)
			{
				Log.Error("Ept >> Encrypt(string enStr) > " + ex.Message);
				return null;
			}
		}
		/// <summary>
		/// 解密方法
		/// </summary>
		/// <param name="deStr">需要解密的字符串</param>
		/// <returns>解密后的字符串</returns>
		public static string DeEncrypt(string deStr)
		{
			try
			{
				DESCryptoServiceProvider des = new DESCryptoServiceProvider();
				byte[] inputByteArray = new byte[deStr.Length / 2];
				for (int x = 0; x < deStr.Length / 2; x++)
				{
					int i = (Convert.ToInt32(deStr.Substring(x * 2, 2), 16));
					inputByteArray[x] = (byte)i;
				}
				//建立加密对象的密钥和偏移量，此值重要，不能修改
				des.Key = ASCIIEncoding.ASCII.GetBytes(myKey);
				des.IV = ASCIIEncoding.ASCII.GetBytes(myKey);
				MemoryStream ms = new MemoryStream();
				CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
				cs.Write(inputByteArray, 0, inputByteArray.Length);
				cs.FlushFinalBlock();
				//建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象
				return Encoding.Default.GetString(ms.ToArray());
			}
			catch (Exception ex)
			{
				Log.Error("Ept >> DeEncrypt(string deStr) > " + ex.Message);
				return null;
			}
		}

		/// <summary>
		/// MD5方式加密
		/// </summary>
		/// <param name="enStr"></param>
		/// <returns></returns>
		public static string Md5Encrypt(string enStr)
        {
			MD5CryptoServiceProvider md = new MD5CryptoServiceProvider();
			return BitConverter.ToString(md.ComputeHash(Encoding.UTF8.GetBytes(enStr))).Replace("-", "");
		}
	}
}
